package com.tanhua.server.controller;

import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.dubbo.api.UserApi;

import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Reference
    private UserApi userApi;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据手机号查询用户
     *
     * @param mobile
     * @return
     */
    @GetMapping("/findByMobile")
    public ResponseEntity<Object> findByMobile(String mobile) {
        int i = 1 / 0;
        return userService.findByMobile(mobile);
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @PostMapping
    public Long save(@RequestBody User user) {
        Long userId = userApi.save(user);
        return userId;
    }

    /**
     * 接口名称：登录第一步---手机号登录
     * 接口路径：POST/user/login
     * 需求描述：根据手机号码，发送验证码
     */
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> paramMap) {
        log.info("接口名称:登录第一步---手机号登录");
        String phone = paramMap.get("phone");
        return userService.sendSms(phone);
    }

    /**
     * 接口名称：登录第二步---验证码校验
     * 接口路径：POST/user/loginVerification
     * 需求分析：根据用户输入的验证码，获取redis中验证码校验。
     */
    @PostMapping("/loginVerification")
    public ResponseEntity<Object> loginVerification(@RequestBody Map<String, String> paramMap) {
        log.info("登录第二步---验证码校验");
        String phone = paramMap.get("phone");
        String verificationCode = paramMap.get("verificationCode");
        return userService.loginVerification(phone, verificationCode);
    }

    /**
     * 接口名称：新用户---1填写资料
     * 接口路径：POST/user/loginReginfo
     * 需求描述：用户第一次登陆，需要完善用户信息
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity<Object> loginReginfo(@RequestBody UserInfo userInfo) {
        log.info("新用户---1填写资料");
        return userService.saveUserInfo(userInfo);
    }

    /**
     * 完善用户信息 - 上传用户头像（修改UserInfo中头像字段）
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity<Object> updateUserHead(
            MultipartFile headPhoto) throws IOException {
        return userService.updateUserHead(headPhoto);
    }

}
